package com.itheima.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.service.MenuService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    private MenuService menuService;

    @RequestMapping("/findMenuList")
    @ResponseBody
    public Result findMenuList(String username){
        try {
            com.itheima.pojo.User user = menuService.findUserWithMenuByUsername(username);
            Set<Role> roles = user.getRoles();
            List<Set<Menu>> userMenu=new ArrayList<>();
            for (Role role : roles) {
                Set<Menu> menus=role.getMenus();
                userMenu.add(menus);
            }

            Set<Map<String,Object>> result=new HashSet<>();
            for (Set<Menu> menus : userMenu) {
                for (Menu parentMenu : menus) {
                    Map<String,Object> parentMap=new HashMap<>();
                    parentMap.put("path",parentMenu.getPath());
                    parentMap.put("title",parentMenu.getName());
                    parentMap.put("icon",parentMenu.getIcon());
                    List<Map<String, Object>> list=new ArrayList<>();
                    for (Menu child : parentMenu.getChildren()) {
                        Map<String,Object> map=new HashMap<>();
                        map.put("path",child.getPath());
                        map.put("title",child.getName());
                        map.put("linkUrl",child.getLinkUrl());
                        map.put("children",child.getChildren());
                        list.add(map);
                    }
                    parentMap.put("children",list);
                    result.add(parentMap);
                }
            }
            System.out.println(JSONUtils.toJSONString(result));
            return new Result(true,"成功",result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"失败");
        }
    }
}
